package ua.zwpp.java8.concurrency;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by vitaly on 17.09.14.
 *
 * If a thread is currently holding the write lock,
 * then any reader thread will get suspended until the write lock is released again
 * http://www.javaspecialists.eu/archive/Issue215.html
 *
 * You can’t have more than one thread inside a critical section (synchronized keyword).
 * ReadWriteLocks were meant to be the perfect solution for this
 */
public class BankAccountReentrantReadWriteLock {
    private final ReadWriteLock lock = new ReentrantReadWriteLock();
    private long balance;

    public BankAccountReentrantReadWriteLock(long balance) {
        this.balance = balance;
    }

    public void deposit(long amount) {
        lock.writeLock().lock();
        try {
            balance += amount;
        } finally {
            lock.writeLock().unlock();
        }
    }

    public void withdraw(long amount) {
        lock.writeLock().lock();
        try {
            balance -= amount;
        } finally {
            lock.writeLock().unlock();
        }
    }

    public long getBalance() {
        lock.readLock().lock();
        try {
            return balance;
        } finally {
            lock.readLock().unlock();
        }
    }
}
